package com.mc.servlet;

import com.mc.bean.Jury;
import com.mc.bean.Student;
import com.mc.bean.Teacher;
import com.mc.service.JuryService;
import com.mc.service.StudentService;
import com.mc.service.TeacherService;
import com.mc.service.impl.JuryServiceImpl;
import com.mc.service.impl.StudentServiceImpl;
import com.mc.service.impl.TeacherServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author wangcf
 * 登录控制器
 */
@WebServlet("/login.action")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JuryService juryService = new JuryServiceImpl();
        TeacherService teacherService = new TeacherServiceImpl();
        StudentService studentService = new StudentServiceImpl();
        String login = req.getParameter("login");
        String tel = req.getParameter("tel");
        String pass = req.getParameter("pass");
        System.out.println(tel+pass);
        HttpSession session = req.getSession();
        Teacher teacher = null;
        Jury jury = null;
        Student student = null;
        if (login.equals("admin")) {
            if (tel.equals("admin") && pass.equals("123")) {
                resp.sendRedirect("index.jsp");
                return;
            }else{
                String mess = "用户名或密码输入错误";
                req.setAttribute("mess1",mess);
                req.getRequestDispatcher("adminlogin.jsp").forward(req,resp);
            }
        } else if (login.equals("user")) {
            String ridStr = req.getParameter("rid");
            int rid = Integer.parseInt(ridStr);
            System.out.println(rid);
            if (rid == 2) {
                jury = juryService.login(tel, pass);
                session.setAttribute("user", jury);
            }
            if (rid == 3) {
                teacher = teacherService.findByTelPass(tel, pass);
                session.setAttribute("user", teacher);
            }
            if (rid == 4) {
                student = studentService.login(tel, pass);
                System.out.println(student);
                session.setAttribute("user", student);
            }
        }
        if (teacher != null || jury != null || student != null) {
            resp.sendRedirect("index.jsp");
        }else{
            String mess = "用户名或密码输入错误";
            req.setAttribute("mess",mess);
            req.getRequestDispatcher("userlogin.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
